<template>
  <div class="ts-auth-info" ref="fullScreen">
    <ts-header title="认证信息" back></ts-header>
    <flex-view>
      <div>
        <div v-if="qualified_status!==2&&type!==2&&status!==1" class="pending"
             :class="{'checking':isChecking(),'faild':isFaild()}"
             @click="readReason">
          <span v-if="isChecking()">审核中</span>
          <span v-if="isFaild()">审核信息未通过，请点击查看原因</span>
        </div>
        <div class="auto-scroll">
          <section class="label-header">
            <label class="title">技能标签<span class="badge">*</span></label>
            <ts-button type="primary" size="mini" @click="next()" plain>
              {{showServiceTypes.length > 0 ? '编辑' : '添加'}}
            </ts-button>
          </section>
          <section class="labels-card" v-for="(item,index) in showServiceTypes" v-if="item.classs.length>0"
                   :key="index">
            <div class="card-header">
              <span class="card-title" v-text="['安装','维修','保养'][item.type_id-1]"></span>
            </div>
            <div class="card-body">
              <div class="card-item" v-for="(prod,pIndex) in item.classs" :key="pIndex">
                <div class="card-row product">
                  <label class="label">产品</label>
                  <span class="value">{{prod.title}}</span>
                </div>
                <div class="card-row brands">
                  <label class="label">品牌</label>
                  <ul class="value">
                    <li class="brands-label" v-for="(brand,bIndex) in prod.brands" :key="bIndex">
                      <span>{{brand.title}}</span></li>
                  </ul>
                </div>
              </div>
            </div>
          </section>
          <uploader class="upd-over" title="资质认证" headTips="最多可上传20张" updTips="上传图片" required
                    footTips="请上传所选服务相对应的资质证明，否则无法通过审核，如有 特殊情况，请联系客服。"
                    v-model="formData.image"
                    @deleteImg="deleteImg"
                    @loadImageUpload="upload"></uploader>
        </div>
      </div>
    </flex-view>
    <ts-button class="submit" type="primary" size="large" @click="chooseAction()">提交</ts-button>
    <mt-actionsheet :actions="actions" v-model="sheetVisible"></mt-actionsheet>
  </div>
</template>

<script>
  import transfer from '../../core/transfer'
  import {SET_REGISTER} from '../../store/mutations-types'
  import {REGISTER, GET_AUTH_INFO, EDIT_AUTH_INFO} from '../../assets/js/api'
  import {Indicator} from 'mint-ui'
  import {convertImgToBase64} from '../../utils/commonUtils'
  import {Actionsheet} from 'mint-ui';
  import objectAssign from 'object-assign'

  let components = {};
  components[Actionsheet.name] = Actionsheet;
  export default {
    name: 'authInfo',
    data() {
      return {
        formData: {
          type: 3,
          tel: null,
          image: [],
          service_types: [],
          token: null
        },
        tempData: null,
        qualified_status: null,
        showServiceTypes: [],
        actions: [{
          name: '拍照',
          method: this.loadImageUpload
        }, {
          name: '从相册选择',
          method: this.loadImageUpload_album
        }],
        sheetVisible: false,
        type: null,
        status: null
      }
    },
    components: components,
    async activated() {
      const {name} = this.$store.state.currentUser
      console.log(status)
      if (!name) {
        this.status = 1;
      } else if(name){
        this.status = null;
      }
      let {member_id, token, tel, type} = this.$store.state.registerRecord;
      this.type = type;
      this.tempData = {member_id, token, tel};
      let json = await this.$http.post(GET_AUTH_INFO, this.tempData, {show: true, type: 'mini'});
      if (json.result === 1) {
        for (let item of Object.keys(json.data)) {
          if (item === 'qualified_status') {
            continue
          }
          this.qualified_status = json.data.qualified_status;
        }
      }
    },
    async created() {
      let {type} = this.$store.state.registerRecord;
      if (type === 2) {
        let {tel, token} = this.$store.state.registerRecord;
        this.formData.tel = tel;
        this.formData.token = token;
        this.$toast({message: '请继续完善认证信息', position: 'bottom', duration: 3000});
      }
      //如果用户已经注册成功，或者已登录
      else {
        //如果注册但是未审核成功
        if (type === 3) {
          this.type = type;
          let {member_id, token, tel} = this.$store.state.registerRecord;
          this.tempData = {member_id, token, tel};
          console.log(token)
        } else if (this.$store.state.currentUser) {
          let {member_id, token, tel} = this.$store.state.currentUser;
          this.tempData = {member_id, token, tel};
        }
        let json = await this.$http.post(GET_AUTH_INFO, this.tempData, {show: true, type: 'mini'});
        this.qualified_status = json.data.qualified_status
        this.showServiceTypes = json.data.authLabels;
        json.data.image.forEach((item, index) => {
          this.formData.image.push(item)
        });
        this.setFormData();
      }
    },
    mounted() {
      transfer.$on('checkComplete', (val) => {
          this.showServiceTypes = [];
          this.showServiceTypes = val;
          this.formData.service_types = [];
          this.setFormData();
        }
      );
    },
    methods: {
      setFormData() {
        for (let item of this.showServiceTypes) {
          if (item.classs.length > 0) {
            let obj = {type_id: item.type_id, classs: []};
            for (let cls of item.classs) {
              let data = {class_id: cls.class_id, brands: []};
              for (let brand of cls.brands) {
                data.brands.push(brand.id)
              }
              obj.classs.push(data);
            }
            this.formData.service_types.push(obj)
          }
        }
      },
      isChecking() {
        return this.qualified_status === 1
      },
      isFaild() {
        return this.qualified_status === 3
      },
      readReason() {
        if (this.qualified_status === 1) {
          return;
        }
        const status = 3;
        this.$router.push({name: 'checkBack', params: {status}});
      },
      next() {
        const skillsLabel = this.showServiceTypes;
        console.log(skillsLabel)
        if (skillsLabel.length !== 0) {
          this.$router.push({name: 'skillsLabel', params: {skillsLabel}})
        } else {
          this.$router.push({name: 'skillsLabel'})
        }
      },
      upload() {
        this.sheetVisible = !this.sheetVisible
      },
      loadImageUpload() {
        let onCameraSuccess = (imageURI) => {
          if (this.formData.image.length <= 20) {
            this.formData.image.push(imageURI);
          } else {
            this.$toast({
              message: '最多可上传20张',
              duration: 1500
            });
          }
        };
        let onCameraError = (message) => {
        };
        if ($prod) {
          navigator.camera.getPicture(onCameraSuccess, onCameraError, {
            //质量
            quality: 100,
            //不允许编辑
            allowEdit: false,
            //获取图片转为base64
            destinationType: Camera.DestinationType.DATA_URL,
            //编码类型JPEG
            encodingType: Camera.EncodingType.JPEG,
            //只允许拍摄图片
            mediaType: Camera.MediaType.PICTURE,
            //按比例缩小图片宽度，单位px,kej
            targetWidth: 375
          });
        } else {
          alert('当前设备不支持')
        }
      },
      loadImageUpload_album() {
        let onCameraSuccess = (imageURI) => {
          if (this.formData.image.length <= 20) {
            this.formData.image.push(imageURI);
          } else {
            this.$toast({
              message: '最多可上传20张',
              duration: 1500
            });
          }
        };
        let onCameraError = (message) => {
        };
        if ($prod) {
          navigator.camera.getPicture(onCameraSuccess, onCameraError, {
            //质量
            quality: 100,
            //不允许编辑
            allowEdit: false,
            //获取图片转为base64
            destinationType: Camera.DestinationType.DATA_URL,
            //编码类型JPEG
            encodingType: Camera.EncodingType.JPEG,
            //只允许拍摄图片
            mediaType: Camera.MediaType.PICTURE,
            //按比例缩小图片宽度，单位px,kej
            sourceType: Camera.PictureSourceType.SAVEDPHOTOALBUM,
            targetWidth: 375,
          });
        } else {
          alert('当前设备不支持')
        }
      },
      deleteImg(index) {
        this.formData.image.splice(index, 1);
      },
      chooseAction() {
        let {type} = this.$store.state.registerRecord;
        if (type === 2) {
          this.addAuthInfo();
        } else {
          this.editAuthInfo();
        }
      },
      token() {
        let {token} = this.$store.state.registerRecord;
        this.formData.token = token;
      },
      async addAuthInfo() {
        this.token();
        if (this.formData.image.length > 0 && this.formData.service_types.length > 0) {
          let {result, member_id} = await this.$http.post(REGISTER, this.formData, {show: true});
          console.log(this.formData)
          if (result === 1) {
            this.$toast('提交成功');
            let {type} = this.$store.state.registerRecord;
            console.log(type)
//            let isFirst = false;
//            if (type === 2) {
//              isFirst = true;
//            }
            this.$store.commit(SET_REGISTER, {type: 3, member_id});
//            this.$router.replace('/register/pending?isFirst=' + isFirst);
            const off = true;
            this.$router.push({name: 'pending', params: {off}})
//            this.$router.replace('/register/pending');
          }
        } else {
          this.$toast({message: '图片或技能不可为空', position: 'bottom'});
        }
      },
      async editAuthInfo() {
        if (this.formData.image.length > 0 && this.formData.service_types.length > 0) {
          let {tel, token, member_id} = this.$store.state.registerRecord;
          console.log(this.$store.state.currentUser)
          this.formData.tel = tel||this.$store.state.currentUser.tel;
          this.formData.token = token;
          console.log(this.formData)
          let json = await this.$http.post(EDIT_AUTH_INFO, objectAssign(this.formData, {member_id}), {show: true});
          if (json.result === 1) {
            let {type} = this.$store.state.registerRecord;
            if (type) {
              let toast = this.$toast('修改成功,等待审核');
              setTimeout(() => {
                toast.close();
                this.$router.push('/register/pending');
              }, 1500)
            } else {
              this.$toast('修改成功');
              this.qualified_status = 1;
            }
          }
        } else {
          this.$toast({message: '图片或技能不可为空', position: 'bottom'});
        }
      }
    },
    computed: {},
    destroyed() {
      let {type} = this.$store.state.registerRecord;
      console.log(type)
    }
  }
</script>

<style lang="scss" scoped>
  @import "../../assets/css/variables";
  @import "../../assets/css/mixin";

  .pending {
    @include sc(.28rem, white);
    text-align: center;
    padding: .23rem 0;
    &.checking {
      background-color: #C6C6C6;
    }
    &.faild {
      background-color: #7BC6FF;
    }
  }

  .ts-auth-info {
    overflow-x: hidden;
    min-height: 100vh;
    background-color: #ffffff;
    .label-header {
      @include fja(space-between);
      padding: .25rem .25rem;
      .title {
        @include sc(.28rem, #020202);
        .badge {
          color: #E91321
        }
      }
    }
    $cardBorder: #E4E4E4;
    .labels-card {
      border-top: .10rem solid $cardBorder;
      .card-header {
        border-bottom: 1px solid $cardBorder;
        padding: .29rem .24rem;
        .card-title {
          @include sc(.24rem, $themeColor)
        }
      }
      .card-body {
        padding: 0 0 .10rem .24rem;
        .card-item {
          padding: .20rem 0 .20rem 0;
          border-bottom: 1px solid $cardBorder;
          &:last-child {
            border-bottom: none;
          }
          .card-row {
            @include sc(.24rem, #2E2E2E);
            .label {
              display: inline-block;
              width: 10%;
            }
            .value {
              display: inline-block;
              width: -moz-calc(90% - .24rem + 4px);
              width: -webkit-calc(90% - .24rem + 4px);
              width: calc(90% - .24rem + 4px);
            }
            &.product {
              margin-bottom: .30rem;
            }
            &.brands {
              .label {
                display: inline-block;
                position: relative;
                top: .10rem;
              }
              .value {
                vertical-align: text-top;
                display: inline-block;
                .brands-label {
                  margin-right: .1rem;
                  border: 1px solid #C6C6C6;
                  border-radius: 3px;
                  padding: .07rem .50rem .08rem;
                  display: inline-block;
                  margin-bottom: .10rem;
                  span {
                    transform: scale(.9);
                    display: block;
                    color: #5D5D5D;
                  }
                }
              }
            }
          }
        }
      }
    }
    .upd-over {
      border-top: .20rem #F6F5F4 solid;
      margin-bottom: 1.80rem;
    }
    .submit {
      border-radius: 0;
    }
  }
</style>
